package com.cby.operation.pay.ui

import android.app.Activity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.cby.operation.common.ext.getId
import com.cby.operation.common.ui.BaseDialogFragment
import com.cby.operation.common.util.CbyLogUtils
import com.cby.operation.pay.PayManager
import com.cby.operation.pay.bean.PayInfo
import com.cby.operation.pay.bean.PayResult
import com.cby.operation.pay.data.PayApiRepository
import com.cby.operation.pay.data.PayLogApiRepository
import com.cby.operation.sdk.*

/**
 * Description:支付结果重新查询
 *
 * @author 陈宝阳
 * @create 2020/10/14 16:13
 */
class PayRetryDialogFragment : BaseDialogFragment() {


    private lateinit var payCloseIv: ImageView
    private lateinit var goodsNameTv: TextView
    private lateinit var payMoneyTv: TextView
    private var payResult: PayResult? = null
    private var payInfo: PayInfo? = null
    private var count = 0

    override fun parseArgs() {
        payResult = arguments.getParcelable(KEY_PAY_RESULT)
        payInfo = payResult?.payInfo
    }

    override fun initView(view: View?) {
        payCloseIv = view!!.findViewById(getId("iv_pay_close"))
        goodsNameTv = view.findViewById(getId("tv_goods_name"))
        payMoneyTv = view.findViewById(getId("tv_pay_money"))
    }

    override fun setContent() {
        if (payInfo != null) {
            goodsNameTv.text = payInfo!!.goodsName
            payMoneyTv.text = "¥ ${payInfo!!.money}"
        }
        startPollingOrder()
    }

    override fun initListener() {
        payCloseIv!!.setOnClickListener {
            val result = PayResult()
            result.payInfo = payInfo
            result.resultCode = CODE_PAY_RETRY_DIALOG_CLOSE
            result.message = ERR_MSG_PAY_RETRY_DIALOG_CLOSE
            PayManager.instance.handlePayCallBack(result)
            dismiss()
        }
    }

    private fun startPollingOrder() {
        handler.removeMessages(MSG_POLLING)
        handler.sendEmptyMessageDelayed(MSG_POLLING, POLLING_INTERVAL.toLong())
    }

    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            if (msg.what == MSG_POLLING && count < POLLING_MAX_TIME) {
                doWork()
                count++
                CbyLogUtils.i("m3839", "count = $count")
            }
        }
    }

    private fun doWork() {
        PayApiRepository.orderQuery(payResult!!.orderId!!, object : PayApiRepository.OnOrderQueryCallBack {

            override fun onResponse(code: Int, msg: String?) {
                if (code == CODE_ORDER_NOT_FIND && count < POLLING_MAX_TIME) {
                    //继续查询
                    handler.sendEmptyMessageDelayed(MSG_POLLING, POLLING_INTERVAL.toLong())
                } else {
                    //次数置为最大，介绍轮询，相应订单结果给玩家
                    count = POLLING_MAX_TIME
                    //这边将支付成功的code强制转为9000
                    handlePayResult(if (code == CODE_SUCCESS) 9000 else code, msg.toString())
                    //支付结果上报
                    payResultReport(code, msg.toString())
                }
            }
        })
    }

    private fun payResultReport(code: Int, msg: String) {
        val content = if (code == CODE_SUCCESS) "ok" else msg
        payResult!!.orderId?.let { PayLogApiRepository.payReport(it, content) }
    }

    private fun handlePayResult(code: Int, resultInfo: String) {
        val result = PayResult()
        result.payInfo = payInfo
        result.resultCode = code
        result.message = resultInfo
        result.payChannel = payResult!!.payChannel
        result.orderId = payResult!!.orderId
        PayManager.instance.showPayResultDialog(result)
        dismissAllowingStateLoss()
    }

    override fun layoutName(): String {
        return "pay_retry_dialog_fragment"
    }

    companion object {
        private const val MSG_POLLING = 101
        private const val POLLING_INTERVAL = 1000
        private const val POLLING_MAX_TIME = 5
        fun show(activity: Activity, payResult: PayResult?): PayRetryDialogFragment {
            val fragment = PayRetryDialogFragment()
            val data = Bundle()
            data.putParcelable(KEY_PAY_RESULT, payResult)
            fragment.arguments = data
            fragment.show(activity.fragmentManager, TAG_FRAGMENT_PAY_RETRY)
            return fragment
        }
    }
}